package com.itheima.servlet;

import com.itheima.bean.student1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

//封装对象反射方式
@WebServlet("/demo5")
public class demo5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.获取所有的数据
        Map<String, String[]> map = req.getParameterMap();

//        2.封装学生对象
        student1 stu = new student1();
//        2.1遍历集合
        for (String key : map.keySet()) {
            String[] values = map.get(key);
//        2.2获取student对象的属性描述器

            try {
                PropertyDescriptor pd= new PropertyDescriptor(key, stu.getClass());
                Method writeMethod = pd.getWriteMethod();

                if(values.length>1){
                    writeMethod.invoke(stu,(Object)values);
                }else {
                    writeMethod.invoke(stu,values);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(stu);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
